package cn.com.winning.ecare.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.expandable.ActionSlideExpandableListView;
import cn.com.winning.ecare.utils.HTTPGetTool;
import cn.com.winning.ecare.utils.URLUtils;
import cn.com.winning.ecare.utils.UserRecord;
import cn.com.winning.ecare.widgets.CustomProgressDialog;

/**院内导航
 * @author Administrator
 *
 */
public class Yndh extends Activity
{

	private Yndh oThis = this;
	private static final int WHAT_DID_LOAD_NEXT = 0;
	private static final int WHAT_DID_LOAD_LAST = 1;
	private static final int WHAT_DID_LOAD_LAST_MEG = 2;
	private static final int WHAT_DID_LOAD_FIRST_MEG = 3;
	private static final int WHAT_DID_LOAD_SEARCH = 4;
	private static final int WHAT_DID_LOAD_SEARCH_MEG = 5;
	private ActionSlideExpandableListView listView;
	private List<Map<String, Object>> listmain = new ArrayList<Map<String, Object>>();
	MyAdapter myAdapter = null;
	MyApplication myApplication;
	CustomProgressDialog proDialog;// 加载框
	int pid = 0;
	int id = 0;
	String nodename = "";
	String node = "";

	private TextView yndh_current = null;
	private ImageButton yndh_preview = null;
	private List<String> list = new ArrayList<String>();
	private EditText yndh_search = null;
	private ImageView yndh_search_btn = null;
	private ImageButton mainselected;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{

		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.yndh);
		myApplication = (MyApplication) getApplication();
		myApplication.addActivity(this);
		myApplication.getUserRecords().setUsername(myApplication.getAccount());
		myApplication.getUserRecords().setModule("Yndh@院内导航");
		UserRecord.getInstance(myApplication.getUserRecords()).init();
		findViews();
		setListener();
		proDialog = CustomProgressDialog.createDialog(oThis);
		proDialog.show();
		proDialog.setCanceledOnTouchOutside(false);
		new Thread(new InitNextData_()).start();
		
		
	}

	private void findViews()
	{
		listView = (ActionSlideExpandableListView) findViewById(R.id.yndh_list);
		yndh_current = (TextView) findViewById(R.id.yndh_current);
		yndh_preview = (ImageButton) findViewById(R.id.yndh_preview);
		yndh_search = (EditText) findViewById(R.id.yndh_search);
		yndh_search_btn = (ImageView) findViewById(R.id.yndh_search_btn);
		mainselected = (ImageButton) this.findViewById(R.id.mainselected);

	}

	private void setListener()
	{
		listView.setOnItemClickListener(null);

		// listView.setOnItemClickListener(new OnItemClickListener()
		// {
		//
		// @Override
		// public void onItemClick(AdapterView<?> adapterview, View view, int i,
		// long l)
		// {
		// HashMap<String, String> map = (HashMap<String, String>) adapterview
		// .getItemAtPosition(i);
		// id = Integer.valueOf(String.valueOf(map.get("id")));
		// String name = String.valueOf(map.get("text"));
		// proDialog = CustomProgressDialog.createDialog(oThis);
		// proDialog.show();
		// proDialog.setCanceledOnTouchOutside(false);
		// new Thread(new InitNextData_()).start();
		// }
		// });
		yndh_preview.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View view)
			{
				proDialog = CustomProgressDialog.createDialog(oThis);
				proDialog.show();
				proDialog.setCanceledOnTouchOutside(false);
				new Thread(new InitLastData_()).start();
			}
		});

		yndh_search_btn.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				String node = yndh_search.getText().toString();
				if ("".equals(node))
				{
					Toast.makeText(oThis, "请输入要查询的科室!", Toast.LENGTH_SHORT).show();
				}
				else
				{
					oThis.node = node;
					new Thread(new InitSearchData_()).start();
				}
			}
		});
		mainselected.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View view)
			{

				Intent intent = new Intent();
				intent.setClass(oThis, Mainmean.class);
				startActivity(intent);
				oThis.finish();
			}
		});

	}

	private Handler myHandler = new Handler()
	{

		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			switch (msg.what)
			{
				case WHAT_DID_LOAD_NEXT:
				{
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					listmain = (List<Map<String, Object>>) msg.obj;
					if (myAdapter == null)
					{
						myAdapter = new MyAdapter();
					}
					listView.setAdapter(myAdapter);
					myAdapter.notifyDataSetChanged();// 更新ExpandableListView
					yndh_current.setText(nodename);
					break;
				}
				case WHAT_DID_LOAD_LAST:
				{
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					listmain = (List<Map<String, Object>>) msg.obj;
					if (myAdapter == null)
					{
						myAdapter = new MyAdapter();
					}
					listView.setAdapter(myAdapter);
					myAdapter.notifyDataSetChanged();// 更新ExpandableListView
					yndh_current.setText(nodename);
					break;
				}
				case WHAT_DID_LOAD_LAST_MEG:
				{
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					Toast.makeText(oThis, (String) msg.obj, Toast.LENGTH_SHORT).show();
					break;
				}
				case WHAT_DID_LOAD_FIRST_MEG:
				{
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					oThis.onBackPressed();
					break;
				}
				case WHAT_DID_LOAD_SEARCH:
				{
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					listmain = (List<Map<String, Object>>) msg.obj;
					if (myAdapter == null)
					{
						myAdapter = new MyAdapter();
					}
					listView.setAdapter(myAdapter);
					myAdapter.notifyDataSetChanged();// 更新ExpandableListView
					yndh_current.setText(nodename);
					break;
				}
				case WHAT_DID_LOAD_SEARCH_MEG:
				{
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					Toast.makeText(oThis, (String) msg.obj, Toast.LENGTH_SHORT).show();
					break;
				}
			}

		}

	};

	/**
	 * 自定义listview布局显示内容 个人档案界面自定义显示内容
	 * 
	 * @author zjj
	 */
	class MyAdapter extends BaseAdapter
	{

		public int getCount()
		{

			return listmain.size();
		}

		public Object getItem(int position)
		{

			return listmain.get(position);
		}

		public long getItemId(int position)
		{

			return position;
		}

		public View getView(final int position, View convertView, ViewGroup parent)
		{

			ViewHolder holder = null;

			if (convertView == null)
			{

				holder = new ViewHolder();

				convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.yndh_item, null);

				holder.yndh_item_mc = (TextView) convertView.findViewById(R.id.yndh_item_mc);
				holder.yndh_item_memo = (TextView) convertView.findViewById(R.id.yndh_item_memo);
				holder.yndh_item_detail = (TextView) convertView.findViewById(R.id.yndh_item_detail);
				holder.expandable_toggle_button = (LinearLayout) convertView.findViewById(R.id.expandable_toggle_button);

				convertView.setTag(holder);

			}

			else
			{
				holder = (ViewHolder) convertView.getTag();

			}
			holder.yndh_item_mc.setText(listmain.get(position).get("text").toString());
			if (!"".equals(listmain.get(position).get("remark").toString()))
			{
				holder.yndh_item_memo.setText(listmain.get(position).get("remark").toString());
				holder.yndh_item_memo.setVisibility(View.VISIBLE);
			}
			if (!"".equals(listmain.get(position).get("address").toString()))
			{
				holder.yndh_item_detail.setText(listmain.get(position).get("address").toString());
				holder.yndh_item_detail.setVisibility(View.VISIBLE);
				Drawable nav_up=getResources().getDrawable(R.drawable.arrow_expand);
				nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
				holder.yndh_item_memo.setCompoundDrawables(null, null, nav_up, null);
				holder.yndh_item_memo.setTextColor(getResources().getColor(R.color.lighttextcolor));
			}

			holder.yndh_item_mc.setOnClickListener(new OnClickListener()
			{

				@Override
				public void onClick(View v)
				{
					id = Integer.valueOf(String.valueOf(listmain.get(position).get("id")));
					proDialog = CustomProgressDialog.createDialog(oThis);
					proDialog.show();
					proDialog.setCanceledOnTouchOutside(false);
					new Thread(new InitNextData_()).start();

				}
			});
			return convertView;
		}

	}

	static class ViewHolder
	{

		TextView yndh_item_mc = null;
		TextView yndh_item_memo = null;
		TextView yndh_item_detail = null;
		LinearLayout expandable_toggle_button = null;
	}

	class InitSearchData_ implements Runnable
	{

		@Override
		public void run()
		{

			Looper.prepare();
			initSearchData();
			Looper.loop();
		}

	}

	private void initSearchData()
	{
		try
		{
			Message msg = myHandler.obtainMessage();
			List<Map<String, Object>> templist = new ArrayList<Map<String, Object>>();
			List<NameValuePair> ls = new ArrayList<NameValuePair>();
			ls.add(new BasicNameValuePair("id", String.valueOf(id)));
			ls.add(new BasicNameValuePair("nodename", node));
			JSONObject json = HTTPGetTool.getTool().post(URLUtils.HOST + URLUtils.YNDHXXFINDSEARCHTREE, ls);

			if (json != null)
			{
				if (json.getBoolean("succ"))
				{
					// 获取科室信息
					JSONArray jsonArr = json.getJSONArray("orglist");
					JSONObject js = null;
					for (int i = 0; i < jsonArr.length(); i++)
					{
						js = jsonArr.getJSONObject(i);
						Map<String, Object> map_main = new HashMap<String, Object>();
						map_main.put("id", js.getInt("id"));
						map_main.put("PId", js.getInt("PId"));
						map_main.put("showOrder", js.getInt("showOrder"));
						map_main.put("address", js.getString("address"));
						map_main.put("nodename", js.getString("nodename"));
						map_main.put("remark", js.getString("remark"));
						map_main.put("text", js.getString("text"));
						templist.add(map_main);
					}
					pid = json.getInt("pid");
					nodename = json.getString("nodename");
					msg.what = WHAT_DID_LOAD_SEARCH;
					msg.obj = templist;
				}
				else
				{
					msg.what = WHAT_DID_LOAD_SEARCH_MEG;
					msg.obj = "没有查到相关科室！";
				}

			}
			else
			{
				msg.what = WHAT_DID_LOAD_LAST_MEG;
				msg.obj = "网络连接错误！";
			}

			myHandler.sendMessage(msg);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	class InitNextData_ implements Runnable
	{

		@Override
		public void run()
		{

			Looper.prepare();
			initNextData();
			Looper.loop();
		}

	}

	private void initNextData()
	{
		try
		{
			Message msg = myHandler.obtainMessage();
			List<Map<String, Object>> templist = new ArrayList<Map<String, Object>>();
			List<NameValuePair> ls = new ArrayList<NameValuePair>();
			ls.add(new BasicNameValuePair("id", String.valueOf(id)));
			JSONObject json = HTTPGetTool.getTool().post(URLUtils.HOST + URLUtils.YNDHXXFINDNEXTTREE, ls);

			if (json != null)
			{
				if (json.getBoolean("succ"))
				{
					// 获取科室信息
					JSONArray jsonArr = json.getJSONArray("orglist");
					JSONObject js = null;
					for (int i = 0; i < jsonArr.length(); i++)
					{
						js = jsonArr.getJSONObject(i);
						Map<String, Object> map_main = new HashMap<String, Object>();
						map_main.put("id", js.getInt("id"));
						map_main.put("PId", js.getInt("PId"));
						map_main.put("showOrder", js.getInt("showOrder"));
						map_main.put("address", js.getString("address"));
						map_main.put("nodename", js.getString("nodename"));
						map_main.put("remark", js.getString("remark"));
						map_main.put("text", js.getString("text"));
						templist.add(map_main);
					}
					pid = json.getInt("pid");
					nodename = json.getString("nodename");
					msg.what = WHAT_DID_LOAD_NEXT;
					msg.obj = templist;
				}
				else
				{
					msg.what = WHAT_DID_LOAD_LAST_MEG;
					msg.obj = "已到达底部！";
				}

			}
			else
			{
				msg.what = WHAT_DID_LOAD_LAST_MEG;
				msg.obj = "网络连接错误！";
			}

			myHandler.sendMessage(msg);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	class InitLastData_ implements Runnable
	{

		@Override
		public void run()
		{

			Looper.prepare();
			initLastData();
			Looper.loop();
		}

	}

	private void initLastData()
	{
		try
		{
			Message msg = myHandler.obtainMessage();
			List<Map<String, Object>> templist = new ArrayList<Map<String, Object>>();
			List<NameValuePair> ls = new ArrayList<NameValuePair>();
			ls.add(new BasicNameValuePair("pid", String.valueOf(pid)));
			JSONObject json = HTTPGetTool.getTool().post(URLUtils.HOST + URLUtils.YNDHXXFINDLASTTREE, ls);

			if (json != null)
			{
				if (json.getBoolean("succ"))
				{
					// 获取科室信息
					JSONArray jsonArr = json.getJSONArray("orglist");
					JSONObject js = null;
					for (int i = 0; i < jsonArr.length(); i++)
					{
						js = jsonArr.getJSONObject(i);
						Map<String, Object> map_main = new HashMap<String, Object>();
						map_main.put("id", js.getInt("id"));
						map_main.put("PId", js.getInt("PId"));
						map_main.put("showOrder", js.getInt("showOrder"));
						map_main.put("address", js.getString("address"));
						map_main.put("nodename", js.getString("nodename"));
						map_main.put("remark", js.getString("remark"));
						map_main.put("text", js.getString("text"));
						templist.add(map_main);
						pid = js.getInt("PId");
					}
					nodename = json.getString("nodename");
					msg.what = WHAT_DID_LOAD_LAST;
					msg.obj = templist;
				}
				else
				{
					msg.what = WHAT_DID_LOAD_FIRST_MEG;
				}

			}
			else
			{
				msg.what = WHAT_DID_LOAD_LAST_MEG;
				msg.obj = "网络连接错误！";
			}

			myHandler.sendMessage(msg);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	// 返回键监听
		@Override
		public boolean onKeyDown(int keyCode, KeyEvent event)
		{
			// TODO Auto-generated method stub
			if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
			{
				proDialog = CustomProgressDialog.createDialog(oThis);
				proDialog.show();
				proDialog.setCanceledOnTouchOutside(false);
				new Thread(new InitLastData_()).start();
			}
			return super.onKeyUp(keyCode, event);
		}
}
